/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.screw.engine;

import java.io.File;
import java.io.IOException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.util.lang.Assert;
import org.elsfs.cloud.common.util.lang.StringUtils;
import org.elsfs.cloud.screw.constant.ScrewConstants;

/**
 * AbstractProduce
 *
 * @author SanLi Created by qinggang.zuo@gmail.com / 2689170096@qq.com on 2020/3/17 21:47
 */
@Data
@Slf4j
public abstract class AbstractTemplateEngine implements TemplateEngine {

  /** 模板配置 */
  private EngineConfig engineConfig;

  private AbstractTemplateEngine() {}

  public AbstractTemplateEngine(EngineConfig engineConfig) {
    Assert.notNull(engineConfig, "EngineConfig can not be empty!");
    this.engineConfig = engineConfig;
  }

  /**
   * 获取文件，文件名格式为，数据库名_版本号.文件类型
   *
   * @param docName 文档名称
   * @return {@link String}
   */
  protected File getFile(String docName) {
    File file;
    // 如果没有填写输出路径，默认当前项目路径下的doc目录
    if (StringUtils.isBlank(getEngineConfig().getFileOutputDir())) {
      String dir = System.getProperty("user.dir");
      file = new File(dir + "/doc");
    } else {
      file = new File(getEngineConfig().getFileOutputDir());
    }
    // 不存在创建
    if (!file.exists()) {
      // 创建文件夹
      boolean mkdir = file.mkdirs();
    }
    // 文件后缀
    String suffix = getEngineConfig().getFileType().getFileSuffix();
    file = new File(file, docName + suffix);
    // 设置文件产生位置
    getEngineConfig().setFileOutputDir(file.getParent());
    return file;
  }

  /** 打开文档生成的输出目录 */
  protected void openOutputDir() throws IOException {
    // 是否打开，如果是就打开输出路径
    if (getEngineConfig().isOpenOutputDir()
        && StringUtils.isNotBlank(getEngineConfig().getFileOutputDir())) {
      // 获取系统信息
      String osName = System.getProperty("os.name");
      if (osName != null) {
        if (osName.contains(ScrewConstants.MAC)) {
          Runtime.getRuntime().exec("open " + getEngineConfig().getFileOutputDir());
        } else if (osName.contains(ScrewConstants.WINDOWS)) {
          Runtime.getRuntime().exec("cmd /c start " + getEngineConfig().getFileOutputDir());
        }
      }
    }
  }
}
